//
//  bussineDataService.m
//  EsayBuy
//
//  Created by 颜 梁坚 on 13-8-20.
//  Copyright (c) 2013年 asiainfo-linkage. All rights reserved.
//

#import "bussineDataService.h"
#import "AppDelegate.h"
//#import "UIDevice-Reachability.h"
//#import "AreaLog.h"
//#import "CityLog.h"
//#import "ProLog.h"

@implementation bussineDataService

@synthesize target;
@synthesize httpCnctor;
@synthesize sendMessageSelector;
@synthesize receiveString;
@synthesize sendDataDic;
@synthesize sendString;
@synthesize rspInfo;
@synthesize updateUrl;
@synthesize HasLogIn;
@synthesize TuiSongDic;
@synthesize loginInfo;
@synthesize LogInHttp;
@synthesize serversUrl;
@synthesize isShowHUD;
@synthesize HUDStatusString;

-(void)dealloc
{
	[receiveString release];
    [serversUrl release];
	[sendDataDic release];
	[sendString release];
    [httpCnctor release];
    if(rspInfo != nil){
        [rspInfo release];
    }
    if(loginInfo != nil){
        [loginInfo release];
    }
    if(TuiSongDic != nil){
        [TuiSongDic release];
    }
    [super dealloc];
}

#pragma mark -
#pragma mark bussineDataService inferface

// 单实例模式
static bussineDataService *sharedBussineDataService = nil;
// 单实例模式
static bussineDataService *sharedBussineDataServicee = nil;

+(bussineDataService*)sharedDataService {
    
    @synchronized ([bussineDataService class]) {
        if (sharedBussineDataService == nil) {
			sharedBussineDataService = [[bussineDataService alloc] sharedInit];
            sharedBussineDataService.isShowHUD = YES;
            return sharedBussineDataService;
        }
    }
    sharedBussineDataService.isShowHUD = YES;
    return sharedBussineDataService;
}

+(bussineDataService*)sharedDataServicee {
    
    @synchronized ([bussineDataService class]) {
        if (sharedBussineDataServicee == nil) {
            sharedBussineDataServicee = [[bussineDataService alloc] sharedInite];
            sharedBussineDataServicee.isShowHUD = YES;
            return sharedBussineDataServicee;
        }
    }
    sharedBussineDataServicee.isShowHUD = YES;
    return sharedBussineDataServicee;
}


-(id)sharedInite
{
    if (self = [super init]) {
        HttpConnector* _httpConnector = [[HttpConnector alloc] init];
        _httpConnector.serviceUrl = service_urlqq;
        self.serversUrl = service_urlqq;
        _httpConnector.isPostXML = NO;
        _httpConnector.statusDelegate = self;
        self.HasLogIn=NO;
        [_httpConnector setTimeout:20];
        [self setHttpCnctor:_httpConnector];
        [_httpConnector release];
    }
    
    return self;
}
-(id)sharedInit
{
	if (self = [super init]) {
		HttpConnector* _httpConnector = [[HttpConnector alloc] init];
        
		_httpConnector.serviceUrl = service_url;
        self.serversUrl = service_url;
        _httpConnector.isPostXML = NO;
		_httpConnector.statusDelegate = self;
        self.HasLogIn=NO;
        [_httpConnector setTimeout:20];
        [self setHttpCnctor:_httpConnector];
        [_httpConnector release];
        
        
	}
	
	return self;
}

- (void)sharedSendMessage:(id <MessageDelegate>)msg synchronously:(BOOL)isSynchronous
{
    self.httpCnctor.serviceUrl = self.serversUrl;
    self.httpCnctor.allowCompressed = YES;
    NSString* sessionId = [[NSUserDefaults standardUserDefaults] objectForKey:@"sessionId"];
    if(sessionId == nil){
        sessionId = @"";
    }
    MyLog(@"sessionId:%@",sessionId);
    if([msg isHouTai]){
        MyLog(@"请求的地址：%@",self.httpCnctor.serviceUrl);
        [self.httpCnctor sendMessage:msg synchronously:NO SessionId:sessionId];
    }else{

        if (isShowHUD) {
            if (HUDStatusString != nil &&HUDStatusString.length>0) {
                [SVProgressHUD showWithStatus:HUDStatusString];
            }else{
                [SVProgressHUD show];
            }
            
        }
        
        
#ifdef STATIC_XML
        NSString* xmlFile = [[NSString alloc] initWithString:[[NSBundle mainBundle]
                                                              pathForResource:[msg getBusinessCode]
                                                              ofType:@"json"]];

        [self.httpCnctor sendMessage_static:msg xmlFile:xmlFile];
        [xmlFile release];
#else
        NSLog(@"请求的地址：%@",self.httpCnctor.serviceUrl);
        
        [self.httpCnctor sendMessage:msg synchronously:NO SessionId:sessionId];
#endif
    }
//    MyLog(@"%@\n %@",self.httpCnctor.httpRequest.requestHeaders,self.httpCnctor.httpRequest.userInfo);
}

-(NSDictionary*)handleRspInfo:(message *) msg
{
    NSString* rspCode = [msg getRspcode];
    NSString* bussineCode = msg.bizCode;
    NSString* rspDesc = [msg getMSG];
    //key: bussineCode value :; Key:errorCode, value: key:MSG, value:
    NSMutableDictionary* rspDic = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
    [rspDic setObject:msg forKey:@"MESSAGE_OBJECT"];
    [rspDic setObject:rspCode forKey:@"errorCode"];
    [rspDic setObject:bussineCode forKey:@"bussineCode"];
    if (rspDesc != nil) {
        [rspDic setObject:rspDesc forKey:@"MSG"];
    }
    
    if ([rspCode isEqualToString:@"0001"]) {
//        [MBProgressHUD hideHUDForView:[AppDelegate shareMyApplication].window animated:YES];
        UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"提示"
                                                            message:@"登录超时，请重新登录！"//Session 过期
                                                           delegate:self
                                                  cancelButtonTitle:@"确定"
                                                  otherButtonTitles:nil];
        alertView.tag = kSessionTimeOutTag;
        [alertView show];
        [alertView release];
        return nil;
    }
    
    return rspDic;
}

-(void)noticeUI:(NSDictionary*)rspDic
{
    
    NSLog(@"\n\n\n  回调信息 %@  \n\n ",rspDic);
    if (rspDic == nil) {
        return;
    }
    NSString* rspCode = [rspDic objectForKey:@"errorCode"];
    id<MessageDelegate> msg = [rspDic objectForKey:@"MESSAGE_OBJECT"];
    
    if ([rspCode isEqualToString:@"0001"]) {
//        [MBProgressHUD hideHUDForView:[AppDelegate shareMyApplication].window animated:YES];
        UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"提示"
                                                            message:@"Session 过期，请重新登陆！"
                                                           delegate:self
                                                  cancelButtonTitle:@"确定"
                                                  otherButtonTitles:nil];
        alertView.tag = kSessionTimeOutTag;
        [alertView show];
        [alertView release];
        return;
    }
    
    if([rspCode isEqualToString:@"0000"]){
        if (nil != self.target && [self.target respondsToSelector:@selector(requestDidFinished:)]) {
            [self.target performSelector:@selector(requestDidFinished:) withObject:rspDic];
        }
    } else {
        if([msg isHouTai]){/*后台设置*/
            NSString* msg = [rspDic objectForKey:@"MSG"];
            if([rspDic objectForKey:@"MSG"] == [NSNull null]){
                msg = @"信息检验异常，请重新登录";
            }
            if(nil == msg){
                msg = @"信息检验异常，请重新登录";
            }
            UIAlertView *aler=[[UIAlertView alloc] initWithTitle:@"提示:" message:@"信息检验异常，请重新登录" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            aler.tag=50505;
            [aler show];
            [aler release];
        }else{
            if (nil != self.target && [self.target respondsToSelector:@selector(requestFailed:)]) {
                [self.target performSelector:@selector(requestFailed:) withObject:rspDic];
            }
        }
    }
}

#pragma make -  准备请求信息
- (void)readySharedSendMessage:(NSString*)messageClaseName
                         param:(NSDictionary*)parameters
                       funName:(NSString*)funName
                 synchronously:(BOOL)synchronously
{
    Class class =  NSClassFromString(messageClaseName);
    message* messageObject = (message*)[[class alloc] init];
    messageObject.requestInfo = parameters;
    SEL selector = NSSelectorFromString(funName);
    [self setSendMessageSelector:selector];
    self.sendDataDic = parameters;
    
    NSLog(@"\n\n  %@     ",self.sendDataDic);
    
    [self sharedSendMessage:messageObject synchronously:synchronously];
    [messageObject release];
}

- (void)readyUploadPhotoMessage:(NSString*)messageClaseName
                         param:(NSDictionary*)parameters
                       funName:(NSString*)funName
                 synchronously:(BOOL)synchronously
                            url:(NSString*)url
                        postKey:(NSString*)key
{
    self.httpCnctor.serviceUrl = url;//image_service_url;
    self.httpCnctor.allowCompressed = NO;
    Class class =  NSClassFromString(messageClaseName);
    message* messageObject = (message*)[[class alloc] init];
    messageObject.requestInfo = parameters;
    SEL selector = NSSelectorFromString(funName);
    [self setSendMessageSelector:selector];
    self.sendDataDic = parameters;
//    [self sharedSendMessage:messageObject synchronously:synchronously];
    [self.httpCnctor uploadPhotoMessage:messageObject synchronously:NO SessionId:@"" PostKey:key];
    [messageObject release];
}

#pragma mark -
#pragma mark alertview delegate
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
	if (kForceUpdateTag == alertView.tag) {
        // 强制升级
        if (alertView.cancelButtonIndex == buttonIndex)
        {
            MyLog(@"updateUrl:%@",self.updateUrl);
            NSURL* url = [NSURL URLWithString:self.updateUrl];
            if([[UIApplication sharedApplication] canOpenURL:url])
            {
                [[NSUserDefaults standardUserDefaults]setValue:@"yes" forKey:@"isFirstOpen"];
                [[NSUserDefaults standardUserDefaults] synchronize];
                [[UIApplication sharedApplication] openURL:url];
            }
            exit(0);
        }
    }
    
    if (kLinkErrorTag == alertView.tag || kTimeOutErrorTag == alertView.tag) {
//         [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:NO];
        //超时或者连接错误，重试
        if (buttonIndex == alertView.firstOtherButtonIndex || buttonIndex == 1) {
            
            NSLog(@"\n\n\n\n\n\n\n\n点击了重试\n\n\n\n\n\n");
            
            if ([self respondsToSelector:sendMessageSelector]) {
                [self performSelector:sendMessageSelector withObject:sendDataDic];
            }
        }
        
        if (buttonIndex == alertView.cancelButtonIndex) {
            if (nil != self.target && [self.target respondsToSelector:@selector(cancelTimeOutAndLinkError)]) {
                [self.target cancelTimeOutAndLinkError];
            }
        }
    }
    
    if (kSessionTimeOutTag == alertView.tag) {
//        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"passWord"];
//        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"logSelf"];
//        //        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"remember"];
//        [[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:@"HuanCun"];
//        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"HuanCunXinxi"];
//        [[NSUserDefaults standardUserDefaults] synchronize];
//        
//        bussineDataService *bus=[bussineDataService sharedDataService];
//        bus.IsTuisong=NO;
//        bus.rspAddrInfo=nil;
//        bus.rspAdInfo=nil;
//        bus.rspStatInfo=nil;
//        bus.rspUserInfo=nil;
//        bus.rspInfo=nil;
//        bus.IsHuanCun=NO;
//        [(AppDelegate *)[UIApplication sharedApplication].delegate relogin];
    }
}




#pragma mark
#pragma mark - 钱咖登陆
- (void)qiankaLogin:(NSDictionary *)paramters
{
    [self readySharedSendMessage:@"QianKaLoginMessage"
                           param:paramters
                         funName:@"qiankaLogin:"
                   synchronously:NO];
}

- (void)qiankaLoginFinished:(id<MessageDelegate>)msg
{
    QianKaLoginMessage *Msg = msg;
    NSDictionary *rspDic = [self handleRspInfo:Msg];
    NSString* rspCode = [Msg getRspcode];
    if([rspCode isEqualToString:@"0000"]){
        self.rspInfo = Msg.rspInfo;
    }
    [self noticeUI:rspDic];
}

/*
 *@brief 退出登录
 */
- (void)usrtLogout:(NSDictionary *)paramters {

        [self readySharedSendMessage:@"UserLogoutMessage"
                               param:paramters
                             funName:@"userLogout:"
                       synchronously:NO];
    
}

-(void)userLogoutFinished:(id<MessageDelegate>)msg
{
    UserLogoutMessage *Msg = msg;
    NSDictionary *rspDic = [self handleRspInfo:Msg];
    NSString* rspCode = [Msg getRspcode];
    if([rspCode isEqualToString:@"0000"]){
        self.rspInfo = Msg.rspInfo;
    }
    [self noticeUI:rspDic];
}


#pragma mark - 实名返档
- (void)sureGuiDang:(NSDictionary *)paramters {
    
        [self readySharedSendMessage:@"RealFangDangMessage"
                               param:paramters
                             funName:@"realFangDang:"
                       synchronously:NO];

}

-(void)realFangDangFinished:(id<MessageDelegate>)msg
{
    RealFangDangMessage *Msg = msg;
    NSDictionary *rspDic = [self handleRspInfo:Msg];
    NSString* rspCode = [Msg getRspcode];
    if([rspCode isEqualToString:@"0000"]){
        self.rspInfo = Msg.rspInfo;
    }
    [self noticeUI:rspDic];
}




#pragma mark -
#pragma mark http 回调接口
- (void)requestDidFinished:(id<MessageDelegate>)msg
{
    [SVProgressHUD dismiss];
    if([[msg getBusinessCode] isEqualToString:QIANKALOGIN_BIZCODE]) {
        [self qiankaLoginFinished:msg];
    }else if ([[msg getBusinessCode] isEqualToString:RealFangDangMessage_BIZCODE]){
        [self realFangDangFinished:msg];
    }else if ([[msg getBusinessCode] isEqualToString:UserLogoutMessage_BIZCODE]){
        [self userLogoutFinished:msg];
    }

}

- (void)requestFailed:(NSDictionary*)errorInfo
{
    [SVProgressHUD dismiss];
	id<MessageDelegate> msg = [errorInfo objectForKey:@"MESSAGE_OBJECT"];
    if([msg isHouTai]){
        MyLog(@"后台");
    }else{
        MyLog(@"不是后台");
//        [MBProgressHUD hideHUDForView:[AppDelegate shareMyApplication].window animated:YES];
        
        NSString* errorCode = [errorInfo objectForKey:@"STATUS_CODE"];
        MyLog(@"%@",errorCode);
        NSString* bussineCode = [msg getBusinessCode];
        NSString* rspDesc = [message getRespondDescription:errorCode];
        
        NSMutableDictionary* rspDic = [[NSMutableDictionary alloc] initWithCapacity:0];
        [rspDic setObject:errorCode forKey:@"errorCode"];
        [rspDic setObject:bussineCode forKey:@"bussineCode"];
        if (rspDesc != nil) {
            [rspDic setObject:rspDesc forKey:@"MSG"];
        }
        
        if ([[message getNetLinkErrorCode] isEqualToString:errorCode]) {
//            [SVProgressHUD dismiss];
//            [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:NO];
            
            UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"提示"
                                                                message:rspDesc
                                                               delegate:self
                                                      cancelButtonTitle:@"取消"
                                                      otherButtonTitles:@"重试",nil];
            alertView.tag = kLinkErrorTag;
            [alertView show];
            [alertView release];
            
            [rspDic release];
            return;
        }
        
        if ([[message getTimeOutErrorCode] isEqualToString:errorCode]) {
//            [SVProgressHUD dismiss];
//            [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:NO];
            
            UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"提示"
                                                                message:rspDesc
                                                               delegate:self
                                                      cancelButtonTitle:@"取消"
                                                      otherButtonTitles:@"重试",nil];
            alertView.tag = kTimeOutErrorTag;
            [alertView show];
            [alertView release];
            
            [rspDic release];
            return;
        }
        
        if (nil != self.target && [self.target respondsToSelector:@selector(requestFailed:)]) {
            [self.target performSelector:@selector(requestFailed:) withObject:rspDic];
        }
        
        [rspDic release];
	}
}

@end
